#include "pollthread.h"
#include <QDir>
#include <QFile>
#include <QStringList>
#include <QDebug>

#ifdef linux
#include <sys/stat.h>
#else
#include <windows.h>
#endif /* linux */

PollThread::PollThread()
{

}

vector<double> PollThread::getTemperature()
{
    vector<double> val;

    tempMutex.lock();
    val = temperature;
    tempMutex.unlock();

    return val;
}

vector<int> PollThread::getLight()
{
    vector<int> val;

    lightMutex.lock();
    val = light;
    lightMutex.unlock();

    return val;
}

void PollThread::run()
{
    vector<double> data;
    vector<int> value;

    while (true) {
        /* Start: 温度 */
        QDir dir("/sys/bus/w1/devices/");
        QStringList nameFilters;

        nameFilters << "28-*";
        QStringList files = dir.entryList(nameFilters, QDir::Dirs|QDir::Readable, QDir::Name);

        data.clear();
        foreach (QString str, files) {
            QFile tmp(dir.path() + "/" + str + "/w1_slave");
            tmp.open(QIODevice::ReadOnly);
            QString info(tmp.readAll());
            tmp.close();
            double val = info.section(QString("t="), 1).toDouble() / 1000.0;
            data.push_back(val);
        }

        QFile tmp2("/sys/devices/virtual/thermal/thermal_zone0/temp");
        if (tmp2.exists()) {
            tmp2.open(QIODevice::ReadOnly);
            QString info(tmp2.readAll());
            tmp2.close();
            double val = info.toDouble() / 1000.0;
            data.push_back(val);
        }

        tempMutex.lock();
        temperature = data;
        tempMutex.unlock();
        /* End: 温度 */

        /* Start: 亮度 */
        value.clear();
        QFile lightFile("/sys/devices/platform/soc/1c2ac00.i2c/i2c-0/0-0023/iio:device0/in_illuminance_raw");
        if (lightFile.exists()) {
            lightFile.open(QIODevice::ReadOnly);
            QString info(lightFile.readAll());
            lightFile.close();
            int val = info.toInt();
            value.push_back(val);
        }

        lightMutex.lock();
        light = value;
        lightMutex.unlock();
        /* End: 亮度 */

        QThread::sleep(1);
    }
}
